package com.dayatang.android.Activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.dayatang.android.Activity.Application.MyApplication;
import com.dayatang.android.Db.ProjectSearchServiceDb;
import com.dayatang.android.Model.Project;
import com.dayatang.android.Model.SubProject;
import com.dayatang.android.Model.User;
import com.dayatang.android.Task.BaseTask;
import com.dayatang.android.Util.HttpUtil;
import com.dayatang.android.config.Config;

public class BaseActivity extends Activity {
	
	private static final String TAG = "Update";
	public ProgressDialog pBar;
	private Handler handler = new Handler();
	
	private boolean keyDownBack = false;
	
	protected ProjectSearchServiceDb projectSearchServiceDb;
	
	private MyApplication application;
	
	public boolean isSaveServerAddress() {
		SharedPreferences sharedPreferences = getSharedPreferences(Config.COMMONDATA, MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE);
		return sharedPreferences.getString(Config.SERVERADDRESS,"").equals("") ? false: true;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.projectSearchServiceDb = new ProjectSearchServiceDb(this);
		this.application  = (MyApplication) this.getApplication();
	}
	
	public String getServerAddress(){
		return application.getServerAddress();
	}
	
	public User getUser(){
		return application.getUser();
	}
	
	public String getRole() {
		return getUser().getRole();
	}
	
	public String getMyTaskNum(){
		return application.getTaskNum();
	}
	
	public Project getCurProject(){
		return application.getProject();
	}
	
	public SubProject getCurSubproject(){
		return application.getSubProject();
	}
	
	public void ManageServerInfo(String info) {
		String result = null;
		if (info.equals(Config.ERROR)) {
			result = getString(R.string.serverAddress_alert_addressError);
		} else if (info.equals(Config.SERVERDIE)) {
			result = getString(R.string.server_go_wrong);
		} else if (info.equals(Config.OTHER)) {
			result = getString(R.string.server_unknown_error);
		} else {
			result = getString(R.string.software_error);
		}
		ToastShow(result);
	}
	
	//判断网络状态
    public boolean chkConnection() { 
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
   		}
    	return netSataus;
    } 
	
    /**
     * 处理返回结果的基本方法
     * @param url
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    public static String getHttpData(Context context, String url) throws InterruptedException, ExecutionException {
    	String result = new BaseTask(context).execute(url).get();
    	if (result.equals(Config.ERROR)) {
    		ToastShow(context,context.getString(R.string.server_unknown_error));
    	} else if (result.equals(Config.SERVERDIE)) {
    		ToastShow(context,context.getString(R.string.server_go_wrong));
    	} else if (result.equals(Config.NODATA)) {
    		ToastShow(context,context.getString(R.string.reports_alert_nofind_data));
    	} else {
    		return result;
    	}
    	return null;
    }
    
	private static void ToastShow(Context context, String toastString) {
		Toast.makeText(context, toastString, Toast.LENGTH_LONG).show();
	}
    
	public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	   		 if (!keyDownBack) {
	   			 ToastShow(getString(R.string.ba_exist_app));
	   			 keyDownBack = true;
	       		 return false;
	   		 } else {
	   			 ActivityManager activityMgr= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
	   			 activityMgr.restartPackage(getPackageName());
	   		 }
		}
		return super.onKeyDown(keyCode, event);
    }
	
	protected static final int INIT_DATA_ID = 0;
	protected static final int OPTIONS_MENU_ID_LOGOUT = 1;
	protected static final int OPTIONS_MENU_ID_PREFERENCES = 2;
	protected static final int OPTIONS_MENU_ID_ABOUT = 3;
	protected static final int OPTIONS_MENU_ID_UPDATE = 13;
	
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		MenuItem item;
		item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0,R.string.omenu_settings);
		item.setIcon(android.R.drawable.ic_menu_preferences);

		item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout);
		item.setIcon(android.R.drawable.ic_menu_revert);

		item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about);
		item.setIcon(android.R.drawable.ic_menu_info_details);

		item = menu.add(0, OPTIONS_MENU_ID_UPDATE, 0, R.string.omenu_upgrade);
		item.setIcon(android.R.drawable.ic_menu_upload);
		
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case OPTIONS_MENU_ID_LOGOUT:
				logout();
				return true;
			case OPTIONS_MENU_ID_PREFERENCES:
				startActivity(new Intent(this,Settings.class));
				break;
			case OPTIONS_MENU_ID_ABOUT:
				Intent intent = new Intent().setClass(this, AboutActivity.class);
				startActivity(intent);
				return true;
			case OPTIONS_MENU_ID_UPDATE:
				getUpdate("update");
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void logout() {
		Dialog dialog = new AlertDialog.Builder(BaseActivity.this)
				.setTitle(getString(R.string.ba_prompt)).setIcon(R.drawable.logo).setMessage(getString(R.string.ba_confirm_logout)).setPositiveButton(getString(R.string.determine), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = new Intent(BaseActivity.this,LoginActivity.class);
						intent.putExtra(Config.LOGOUT, Config.LOGOUT);
						startActivityInRightToLeft(intent);
						finish();
					}
				}).setNegativeButton(getString(R.string.abolish), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create();
		dialog.show();
	}
	
	protected void ToastShow(String toastString) {
		Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();
	}
	
	public void startActivity(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	public void startActivityInRightToLeft(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
	}
	
	public void startActivityByPushLeft(Intent intent) {
		super.startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}
	
	public void finishActivityTransition() {
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
	}
	
	public void finishActivitySlide() {
		overridePendingTransition(R.anim.slide_up_in, R.anim.slide_down_out);
	}
	
	public void finishActivityPushUpIn() {
		overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
	}
	
	protected void getUpdate(String type) {
		try {
			String url = getServerAddress() + "/remote/version-update.action?category=ANDROID&versionCode="+Config.getVerCode(this);
			String result = new BaseTask(this).execute(url).get();
			
			if(!result.equals(Config.NO)){
				doNewVersionUpdate(result);
			}else if(type.equals(Config.UPDATE)){
				notNewVersionShow();
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}

	private void notNewVersionShow() {
		int verCode = Config.getVerCode(this);
		String verName = Config.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append(getString(R.string.ba_current_versions));
		sb.append(verName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append(getString(R.string.ba_new_versions));
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle(getString(R.string.ba_soft_update)).setIcon(R.drawable.logo).setMessage(sb.toString())
				.setPositiveButton(getString(R.string.determine), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create();
		dialog.show();
	}

	private void doNewVersionUpdate(String data) {
		int verCode = Config.getVerCode(this);
		int UpdateVerCode = verCode + 1;
		String verName = Config.getVerName(this);
		StringBuffer sb = new StringBuffer();
		sb.append(getString(R.string.ba_current_versions));
		sb.append(verName);
		sb.append(" Code:");
		sb.append(verCode);
		sb.append(getString(R.string.ba_find_new_versions));
		sb.append(UpdateVerCode+".0");
		sb.append(" Code:");
		sb.append(UpdateVerCode);
		sb.append(getString(R.string.ba_update_explain));
		sb.append(data);
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle(getString(R.string.ba_soft_update))
				.setMessage(sb.toString())
				.setIcon(R.drawable.logo)
				.setPositiveButton(getString(R.string.ba_update),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								pBar = new ProgressDialog(BaseActivity.this);
								pBar.setTitle(getString(R.string.ba_downloading));
								pBar.setIcon(R.drawable.logo);
								pBar.setMessage(getString(R.string.ba_waiting));
								pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
								
								getDownloadFile();
							}
						})
				.setNegativeButton(getString(R.string.ba_not_update),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								dialog.dismiss();
							}
						}).create();
		dialog.show();
	}

	void getDownloadFile(){
		try {
			String url = getServerAddress() + "/remote/download.action?category=ANDROID";
			String result = new BaseTask(this).execute(url).get();
			if(result != null){
				String downUrl = getServerAddress() + "/remote/remote-app-download.action?attachment.id="+result;
				downFile(downUrl);
			}
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}
	
	void downFile(final String address) {
		pBar.show();
		new Thread() {
			public void run() {
				try {
					InputStream is = HttpUtil.getInputStream(address, BaseActivity.this);
					FileOutputStream fileOutputStream = null;
					if (is != null) {
						File file = new File(Environment.getExternalStorageDirectory()+Config.ROOTDIR,Config.APPNAME);
						if(!file.getParentFile().exists()){
							file.getParentFile().mkdirs();
						}
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					down();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	void down() {
		handler.post(new Runnable() {
			public void run() {
				pBar.cancel();
				update();
			}
		});
	}

	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory()+Config.ROOTDIR, Config.APPNAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}
	
}
